package com.example.springmvc.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * @author fanhang
 */
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    private final ObjectMapper objectMapper;
    private final JwtInterceptor jwtInterceptor;
    private final JwtMethodArgumentResolver jwtMethodArgumentResolver;

    public WebMvcConfiguration(ObjectMapper objectMapper, JwtInterceptor jwtInterceptor, JwtMethodArgumentResolver jwtMethodArgumentResolver) {
        this.objectMapper = objectMapper;
        this.jwtInterceptor = jwtInterceptor;
        this.jwtMethodArgumentResolver = jwtMethodArgumentResolver;
    }

    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(jwtMethodArgumentResolver);
        super.addArgumentResolvers(argumentResolvers);
    }

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 雪花ID超Long返回字符串格式
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(module);
        converters.add(0, new MappingJackson2HttpMessageConverter(objectMapper));
        super.configureMessageConverters(converters);
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addWebRequestInterceptor(jwtInterceptor);
        super.addInterceptors(registry);
    }
}
